#include "cvMatConversionQImage.h"

cvMatConversionQImage::cvMatConversionQImage()
{

}

/**
    实现OpenCV中的Mat类转换为QImage
**/
QImage cvMatConversionQImage::Mat2QImage(cv::Mat &mat)
{
    QImage qimg;
    switch(mat.type())
    {
    case CV_8UC4 :
    {
        qDebug("CV_8UC4");
        qimg = QImage( mat.data, mat.cols, mat.rows, mat.step, QImage::Format_RGB32 );
    }
        break;
    case CV_8UC3:
    {
        qDebug ("CV_8UC3");
        //
        //注意, Mat数据是以BGR方式进行存放的,而QImage是以RGB方式存放的,需要将BGR转换为RGB
        //
        cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB);
        qimg = QImage( mat.data, mat.cols, mat.rows, mat.step, QImage::Format_RGB888 );
    }
        break;
    case CV_8UC1:
    {
        qDebug("CV_8UC1");
        qimg = QImage( mat.data, mat.cols, mat.rows, mat.step, QImage::Format_Indexed8 );
    }
        break;
    default:
    {
        qDebug("Image format is not supported: depth=%d and %d channels\n", mat.depth(), mat.channels());

    }
        break;
    }
    return qimg;
}
/**
    实现为QImage 转换为 OpenCV中的Mat类
**/
cv::Mat cvMatConversionQImage::QImage2Mat(QImage &qimg)
{
    cv::Mat mat;
    switch(qimg.format())
    {
    case QImage::Format_RGB32:
    {
        mat = cv::Mat(qimg.height(), qimg.width(), CV_8UC4, const_cast<uchar*>(qimg.bits()), qimg.bytesPerLine());
    }
        break;
    case QImage::Format_RGB888:
    {
        //
        //注意, 而QImage是以RGB方式存放的, Mat是以BGR方式进行存放的,需要将RGB转换为BGR
        //
        QImage swapped = qimg.rgbSwapped(); //将RGB转换为BGR
        mat = cv::Mat( swapped.height(), swapped.width(), CV_8UC3, const_cast<uchar*>(swapped.bits()), swapped.bytesPerLine());
    }
        break;
    case QImage::Format_Indexed8:
    {
        mat = cv::Mat( qimg.height(), qimg.width(), CV_8UC1, const_cast<uchar*>(qimg.bits()), qimg.bytesPerLine());
    }
        break;
    default:
    {
        qDebug("Image format is not supported: depth=%d and %d format\n", qimg.depth(), qimg.format());
    }
        break;
    }
    return mat;
}
